﻿/* Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
 
Copyright (C) 2010 by Tomasz Pluskiewicz

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */

using System;
using Castle.Core;
using Castle.Core.Resource;
using Castle.DynamicProxy;
using Castle.MicroKernel.Registration;
using Castle.MonoRail.Framework;
using Castle.MonoRail.WindsorExtension;
using Castle.Windsor;
using Castle.Windsor.Configuration.Interpreters;
using Yama.MVC.Dao.Repositories;

namespace Yama.MVC.Container
{
    /// <summary>
    /// A Windsor container. 
    /// 
    /// Use this class in your Global application class to easily register repositories and controllers 
    /// </summary>
    public class Container : WindsorContainer
    {
        /// <summary>
        /// Creates a new instance of Container with <see cref="MonoRailFacility">MonoRailFacility</see>
        /// with otherwise empty configurtion
        /// </summary>
        public Container()
        {
            RegisterFacilities();
        }

        ///<summary>
        /// Creates a new instance of Container with <see cref="MonoRailFacility">MonoRailFacility</see>
        ///</summary>
        ///<param name="sectionName">configuration section in app.config or web.config</param>
        public Container(string sectionName)
            : base(new XmlInterpreter(new ConfigResource(sectionName)))
        {
            RegisterFacilities();
        }

        protected void RegisterFacilities()
        {
            AddFacility("rails", new MonoRailFacility());
        }

        ///<summary>
        /// Adds all public controllers implementing <see cref="IController">IController</see> to the container
        /// from the selected Assembly
        ///</summary>
        ///<param name="assemblyName">name of assembly containing controllers</param>
        ///<param name="interceptorTypes">Interceptors added to controllers</param>
        ///<param name="hook"><see cref="IProxyGenerationHook"/> allows choosing which methods to intercetp with <paramref name="interceptorTypes"/></param>
        ///<param name="selector"><see cref="IInterceptorSelector" /> allows choosing interceptors fo specific method</param>
#if NET35
        public void RegisterControllers(string assemblyName, Type[] interceptorTypes, IProxyGenerationHook hook, IInterceptorSelector selector)
#else
        ///<summary>
        /// Adds all public controllers implementing <see cref="IController">IController</see> to the container
        /// from the selected Assembly
        ///</summary>
        ///<param name="assemblyName">name of assembly containing controllers</param>
        ///<param name="interceptorTypes">Interceptors added to controllers</param>
        ///<param name="hook"><see cref="IProxyGenerationHook"/> allows choosing which methods to intercetp with <paramref name="interceptorTypes"/></param>
        ///<param name="selector"><see cref="IInterceptorSelector" /> allows choosing interceptors fo specific method</param>
        public void RegisterControllers(string assemblyName, Type[] interceptorTypes = null, IProxyGenerationHook hook = null, IInterceptorSelector selector = null)
#endif
        {
            this.Register(AllTypes.FromAssemblyNamed(assemblyName)
                              .BasedOn(typeof(IController))
                              .Configure(cr => ConfigureController(cr, interceptorTypes, hook, selector)));
        }

        private static object ConfigureController(ComponentRegistration cr, Type[] interceptorTypes, IProxyGenerationHook hook, IInterceptorSelector selector)
        {
            ComponentRegistration<object> registration = cr.Named(cr.Implementation.Name);

            if (interceptorTypes != null)
                registration.Interceptors(interceptorTypes);

            if (hook != null)
                registration.Proxy.Hook(hook);

            if (selector != null)
                registration.SelectInterceptorsWith(selector);

            return registration;
        }

        ///<summary>
        /// Adds all public view components inheriting <see cref="ViewComponent">ViewComponent</see> to the container
        /// from the selected Assembly
        ///</summary>
        ///<param name="assemblyName">name of assembly containing view components</param>
        public void RegisterViewComponents(string assemblyName)
        {
            this.Register(AllTypes
                              .FromAssemblyNamed(assemblyName)
                              .Pick()
                              .Configure(cr => cr.Named(cr.ServiceType.Name).LifeStyle.Transient));
        }

#if NET35
        ///<summary>
        /// Registers repositories provided by <paramref name="repositoriesProvider"/>
        ///</summary>
        ///<param name="repositoriesProvider">implementation of <see cref="IRepositoriesProvider"/></param>
        ///<param name="lifestyle">Lifestyle used for registering each repository</param>
        public void RegisterRepositories(IRepositoriesProvider repositoriesProvider, LifestyleType lifestyle)
#else
        ///<summary>
        /// Registers repositories provided by <paramref name="repositoriesProvider"/>
        ///</summary>
        ///<param name="repositoriesProvider">implementation of <see cref="IRepositoriesProvider"/></param>
        ///<param name="lifestyle">Lifestyle used for registering each repository</param>
        public void RegisterRepositories(IRepositoriesProvider repositoriesProvider, LifestyleType lifestyle = LifestyleType.PerWebRequest)
#endif
        {
            this.Register(Component
                         .For(typeof (RepositoryFactory))
                         .ImplementedBy(typeof (WindsorRepositoryFactory))
                         .Named("repository.factory")
                         .LifeStyle.Singleton);

            foreach (RepositoryComponentInfo repository in repositoriesProvider.Repositories)
            {
                RepositoryFactory.RegisterRepository(repository.Service);

                this.Register(Component
                             .For(repository.Service)
                             .ImplementedBy(repository.Implementation)
                             .Named(repository.Id)
                             .LifeStyle.Is(lifestyle));
            }
        }
    }
}